﻿using System;

namespace SangsTools
{
    public static class MyRandomTools
    {
        private static Random _Random;
        public static Random random
        {
            get
            {
                if (_Random == null)
                    _Random = new Random();
                return _Random;
            }
        }

        public static int Random(int min, int max)
        {
            return random.Next(min, max);
        }

        //根据权重数组，返回index
        public static int RandomWithWeight(int[] arrWeight)
        {
            if (arrWeight == null || arrWeight.Length == 0)
            {
                return -1;
            }

            int[] arrWeightTarget = new int[arrWeight.Length];
            int weightCount = 0;
            for (int i = 0; i < arrWeightTarget.Length; i++)
            {
                weightCount += arrWeight[i];
                arrWeightTarget[i] = weightCount;
            }

            int tmp = Random(0, weightCount);
            for (int j = 0; j < arrWeightTarget.Length; j++)
            {
                if (tmp < arrWeightTarget[j])
                {
                    return j;
                }
            }
            return -1;
        }

        public static T[] RandomWithWeight<T>(T[] arrItem, int[] arrWeight, int count = 1)
        {
            if (arrItem == null || arrItem.Length == 0 || arrWeight == null || arrWeight.Length == 0 || count <= 0)
            {
                //throw new System.Exception("带权随机参数异常");
                return null;
            }

            int[] arrWeightTarget = new int[arrWeight.Length];
            int weightCount = 0;
            for (int i = 0; i < arrWeightTarget.Length; i++)
            {
                weightCount += arrWeight[i];
                arrWeightTarget[i] = weightCount;
            }

            T[] arrRandom = new T[count];
            for (int i = 0; i < count; i++)
            {
                int tmp = Random(0, weightCount);
                for (int j = 0; j < arrWeightTarget.Length; j++)
                {
                    if (tmp < arrWeightTarget[j])
                    {
                        arrRandom[i] = arrItem[j];
                        break;
                    }
                }
            }
            return arrRandom;
        }
    }
}